﻿using System.Reflection;
using Mapster;
using Mapster.Utils;
using Microsoft.Extensions.DependencyInjection;

namespace Aurora.AutoMapper;

/// <summary>
/// 对象映射扩展
/// </summary>
public static class ModelMapperExtension
{
    /// <summary>
    /// 注入 map ster  注册
    /// </summary>
    /// <param name="services"></param>
    /// <param name="assemblies"></param>
    /// <returns></returns>
    public static IServiceCollection AddMapsterRegister(this IServiceCollection services, params Assembly[]? assemblies)
    {
        // 获取全局映射配置
        var config = TypeAdapterConfig.GlobalSettings;
        assemblies ??= AppDomain.CurrentDomain.GetAssemblies();
        if (assemblies.Length > 0)
        {
            config.Scan(assemblies);
        }

        // 配置默认全局映射 支持覆盖
        config.Default.NameMatchingStrategy(NameMatchingStrategy.Flexible)
            .PreserveReference(true);

        // 配置默认全局映射 忽略大小写敏感
        config.Default.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase)
            .PreserveReference(true);
        // 扫描自定义映射
        // 扫描程序集
        foreach (var assembly in assemblies)
        {
            var types = assembly.GetLoadableTypes().Where(x =>
                    x is { IsAbstract: false, IsClass: true } && typeof(IMappingProfile).IsAssignableFrom(x))
                .ToList();
            // 创建实例
            foreach (var type in types)
            {
                var instance = (IMappingProfile)Activator.CreateInstance(type)!;
                instance.Configure();
            }
        }

        services.AddSingleton(config);
        return services;
    }
}